<?php

class Trans
{
    private $URL = "http://api.fanyi.baidu.com/api/trans/vip/translate";
    private $APP_ID;
    private $SEC_KEY;

    public function __construct($conf)
    {
        $this->APP_ID  = $conf->APP_ID;
        $this->SEC_KEY = $conf->SEC_KEY;
    }

    //翻译入口
    public function run(string $query, string $from = 'en', string $to = 'zh'): array
    {
        $args         = [
            'q'     => $query,
            'appid' => $this->APP_ID,
            'salt'  => rand(10000, 99999),
            'from'  => $from,
            'to'    => $to,
        ];
        $args['sign'] = $this->buildSign($query, $this->APP_ID, $args['salt'], $this->SEC_KEY);
        $ret          = $this->call($this->URL, $args);
        $ret          = json_decode($ret, true);
        if(json_last_error() == JSON_ERROR_NONE){
            return $ret;
        }else{
            return [];
        }
    }

    //加密
    private function buildSign(string $query, string $appID, string $salt, string $secKey): string
    {
        $str = $appID . $query . $salt . $secKey;
        $ret = md5($str);
        return $ret;
    }

    //发起网络请求
    private function call($url, $args = null, $method = "post", $testflag = 0, $timeout = 10, $headers = [])
    {
        $ret = false;
        $i   = 0;
        while ($ret === false) {
            if ($i > 1)
                break;
            if ($i > 0) {
                sleep(1);
            }
            $ret = $this->callOnce($url, $args, $method, false, $timeout, $headers);
            $i++;
        }
        return $ret;
    }

    private function callOnce($url, $args = null, $method = "post", $withCookie = false, $timeout = 10, $headers = [])
    {
        $ch = curl_init();
        if ($method == "post") {
            $data = $this->convert($args);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_POST, 1);
        } else {
            $data = $this->convert($args);
            if ($data) {
                if (stripos($url, "?") > 0) {
                    $url .= "&$data";
                } else {
                    $url .= "?$data";
                }
            }
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        if ($withCookie) {
            curl_setopt($ch, CURLOPT_COOKIEJAR, $_COOKIE);
        }
        $r = curl_exec($ch);
        curl_close($ch);
        return $r;
    }

    private function convert(&$args)
    {
        $data = '';
        if (is_array($args)) {
            foreach ($args as $key => $val) {
                if (is_array($val)) {
                    foreach ($val as $k => $v) {
                        $data .= $key . '[' . $k . ']=' . rawurlencode($v) . '&';
                    }
                } else {
                    $data .= "$key=" . rawurlencode($val) . "&";
                }
            }
            return trim($data, "&");
        }
        return $args;
    }
}

//$tran  = new Trans();
//$query = <<<EOF
//{"title":"Receiving kAUGraphErr_CannotDoInCurrentContext when calling AUGraphStart for playback"}
//EOF;
//print_r($tran->run($query));

/***

$html=<<<EOF

    <li id="comment-27991595" class="comment js-comment " data-comment-id="27991595">
        <div class="js-comment-actions comment-actions">
            <div class="comment-score js-comment-edit-hide">
                    <span title="number of &#39;useful comment&#39; votes received"
                            class="cool">3</span>
            </div>
                    </div>
        <div class="comment-text js-comment-text-and-form">
            <div class="comment-body js-comment-edit-hide">

                <span class="comment-copy">Note: <code>git check-ignore</code> will soon (git1.8.5/1.9) have a <code>--no-index</code> option. See <a href="http://stackoverflow.com/a/18953923/6309">my answer below</a></span>

                    &ndash;&nbsp;<a href="/users/6309/vonc"
                       title="890,534 reputation"
                       class="comment-user">VonC</a>
                <span class="comment-date" dir="ltr"><span title="2013-09-23 07:34:40Z" class="relativetime-clean">Sep 23 '13 at 7:34</span></span>
                                                            </div>
        </div>
    </li>
    <li id="comment-59130438" class="comment js-comment " data-comment-id="59130438">
        <div class="js-comment-actions comment-actions">
            <div class="comment-score js-comment-edit-hide">
            </div>
                    </div>
        <div class="comment-text js-comment-text-and-form">
            <div class="comment-body js-comment-edit-hide">

                <span class="comment-copy">Note: <code>GIT_TRACE_EXCLUDE=1 git status</code> will soon be an additional way to debug <code>.gitignore</code> rules. See <a href="http://stackoverflow.com/a/18953923/6309">my edited answer below</a></span>

                    &ndash;&nbsp;<a href="/users/6309/vonc"
                       title="890,534 reputation"
                       class="comment-user">VonC</a>
                <span class="comment-date" dir="ltr"><span title="2016-03-01 16:09:45Z" class="relativetime-clean">Mar 1 '16 at 16:09</span></span>
                                                            </div>
        </div>
    </li>
    <li id="comment-88631696" class="comment js-comment " data-comment-id="88631696">
        <div class="js-comment-actions comment-actions">
            <div class="comment-score js-comment-edit-hide">
            </div>
                    </div>
        <div class="comment-text js-comment-text-and-form">
            <div class="comment-body js-comment-edit-hide">

                <span class="comment-copy">Relevant blog post: <a href="https://danielcompton.net/2016/04/21/git-check-ignore-explaining-why-git-ignored-file" rel="nofollow noreferrer">danielcompton.net/2016/04/21/&hellip;</a>.</span>

                    &ndash;&nbsp;<a href="/users/946850/krlmlr"
                       title="15,822 reputation"
                       class="comment-user">krlmlr</a>
                <span class="comment-date" dir="ltr"><span title="2018-06-12 09:08:37Z" class="relativetime-clean">Jun 12 '18 at 9:08</span></span>
                                                            </div>
        </div>
    </li>
EOF;

$tran  = new Trans();
preg_match_all('#<div\s+class\=\"comment\-body\s+js\-comment\-edit\-hide\">\s+(.*?)\s+&ndash;&nbsp;<a\s+href\=\"#isu', $html, $trans);
foreach($trans[1] as $k1=>$v1){
	if( preg_match_all('#<code>.*?</code>#isu', $v1, $code)>0 ){
		$ocrstr = preg_replace('#<code>.*?</code>#isu', '{c.o.d.e}', $v1);
		$deal = $tran->run(strip_tags($ocrstr));
		$deal = explode('{c.o.d.e}', $deal['trans_result'][0]['dst']);
		$result = '';
		foreach($deal as $k2=>$v2){
			$result .= $v2;
			if(isset($code[0][$k2])){
				$result .= $code[0][$k2];
			}
		}
	}else{
		$result = $tran->run(strip_tags($v1))['trans_result'][0]['dst'];
	}
	$html = str_replace($v1, $result, $html);
}

echo PHP_EOL . $html .PHP_EOL;
***/
